<?php
/**
 * 锁基类
 * 
 * @author 张军磊 <zhangjunlei26@gmail.com>
 *
 */
class Lock
{
	// 超时规格(秒)，如果为0则不判断锁超时
	protected $timeout = 0;

	protected $locked = array();

	protected static $instance;

	public function __construct (array $options = array())
	{
		$this->set_from($options);
		if ($this->timeout) $this->timeout = intval($this->timeout);
	}

	/**
	 * 设置属性
	 *
	 * @param $options array       	
	 */
	protected function set_from (array $options)
	{
		foreach ($options as $key => $val)
			$this->$key = $val;
	}

	/**
	 * 等待锁并解锁
	 *
	 * @param $key string       	
	 * @param $data string       	
	 * @param $utime integer       	
	 */
	public function wait ($key ,$data = NULL ,$utime = 100000)
	{
		while (! $this->lock($key, $data, TRUE))
		{
			// echo "休息0.1秒再取锁...<br />\r\n";
			usleep($utime);
		}
		return TRUE;
	}

	/**
	 * 解锁当前进程所有锁
	 */
	public function __destruct ()
	{
		if ($this->locked)
		{
			foreach ($this->locked as $key => $val)
				$this->unlock($key);
		}
	}
}